(function setupGlobalModalA11yFix() {
  if (window.__SmarTestModalA11yFixInstalled__) {
    return;
  }
  window.__SmarTestModalA11yFixInstalled__ = true;

  function ensureBodyFocusable() {
    if (!document.body.hasAttribute('tabindex')) {
      document.body.setAttribute('tabindex', '-1');
    }
  }

  function moveFocusOutOf(element) {
    try {
      const active = document.activeElement;
      if (active && element.contains(active)) {
        active.blur();
      }
    } catch (_) {}
    ensureBodyFocusable();
    try { document.body.focus(); } catch (_) {}
  }

  document.addEventListener('show.bs.modal', function (event) {
    const modal = event.target;
    if (!(modal instanceof HTMLElement)) return;
    // 移除aria-hidden与inert，避免显示时依然被隐藏或不可聚焦
    modal.removeAttribute('aria-hidden');
    modal.removeAttribute('inert');
  });

  document.addEventListener('hide.bs.modal', function (event) {
    const modal = event.target;
    if (!(modal instanceof HTMLElement)) return;
    // 隐藏前移除模态框内的焦点，避免aria-hidden作用于仍保留焦点的后代
    moveFocusOutOf(modal);
    // 提前设置inert，阻止动画过程中的意外聚焦
    modal.setAttribute('inert', '');
  });

  document.addEventListener('hidden.bs.modal', function (event) {
    const modal = event.target;
    if (!(modal instanceof HTMLElement)) return;
    // 确保完全隐藏后处于无障碍隐藏状态
    modal.setAttribute('aria-hidden', 'true');
    // 双保险移除残留焦点
    moveFocusOutOf(modal);
  });
})();


